package com.sanyou.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.sanyou.enums.MaintainType;
import com.sanyou.pojo.*;
import com.sanyou.pojo.dto.ProductInfoDTO;
import com.sanyou.pojo.dto.SimpleProductDTO;
import com.sanyou.pojo.vo.*;
import com.sanyou.service.*;
import com.sanyou.utils.JSONResult;
import com.sanyou.utils.PagedResult;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

import static com.sanyou.controller.BasicController.PAGE_SIZE;

/**
 * User: asus
 * Date: 2021-12-14
 * Time: 13:35
 * Version:V1.0
 */
@Api(value = "阴极板相关的接口",tags = {"阴极板相关的Controller"})
@CrossOrigin
@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private FactoryService factoryService;

    @Autowired
    private UserService userService;

    /**
     * 根据条件获取阴极板的信息
     * 信息内容包括检测循环次数、维修次数等
     * @param query
     * @param page
     * @param pageSize
     * @param state
     * @param maintainType
     * @param factoryId
     * @param subFactoryId
     * @param userId
     * @return
     */
    @GetMapping("/query")
    public JSONResult query(String query,Integer page, Integer pageSize,Integer state,
                            Integer maintainType,String factoryId,String subFactoryId,String userId){
        if(page == null)
            page = 1;

        if(pageSize == null)
            pageSize = PAGE_SIZE;

        //分页查询阴极板数据
        PageInfo<ProductVo> pageInfo = productService.listProductInfo(query,state,maintainType,null,null,factoryId,subFactoryId,userId,page,pageSize);
        //封装分页以及记录信息作为返回结果
        PagedResult pagedResult = new PagedResult();
        pagedResult.setPage(pageInfo.getPageNum());
        pagedResult.setTotal(pageInfo.getPages());
        pagedResult.setRecords(pageInfo.getTotal());

        //数据转换
        List<JSONObject> jsonObjects = new ArrayList<>();
        for(ProductVo info:pageInfo.getList()){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", info.getId()); //阴极板id
            jsonObject.put("productCode", info.getProductCode()); //阴极板编码
            jsonObject.put("productPlane", info.getProductPlane()); //平面度
            jsonObject.put("productVert", info.getProductValue()); //垂直度
            jsonObject.put("productState", info.getProductState()); //阴极板状态
            jsonObject.put("createtime", info.getCreatetime()); //创建时间
            jsonObject.put("updateStateDate", info.getUpdateStateDate()); //状态更新日期
            jsonObject.put("maintainType", info.getMaintainType()); //维修类型
            jsonObject.put("updateMaintainDate", info.getUpdateMaintainDate()); //状态更新日期
            jsonObject.put("cycle", info.getCycle()); //循环次数
            jsonObject.put("maintainCycle", info.getMaintainCycle()); //维修次数
            jsonObjects.add(jsonObject);
        }
        pagedResult.setRows(jsonObjects);

        return JSONResult.ok(pagedResult);
    }

    /**
     * 查询阴极板基本信息
     * 用于档案管理中的初始数据模块
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/queryAll")
    public JSONResult queryAll(Integer page, Integer pageSize){

        if(page == null)
            page = 1;

        if(pageSize == null)
            pageSize = PAGE_SIZE;

        //分页查询阴极板数据
        PageInfo<Product> pageInfo = productService.queryAll(page,pageSize);

        //封装分页以及记录信息作为返回结果
        PagedResult pagedResult = new PagedResult();
        pagedResult.setPage(pageInfo.getPageNum());
        pagedResult.setTotal(pageInfo.getPages());
        pagedResult.setRecords(pageInfo.getTotal());
        pagedResult.setRows(pageInfo.getList());

        return JSONResult.ok(pagedResult);
    }

    @PostMapping("/updateProduct")
    public JSONResult updateProduct(@RequestBody ProductVo productVo){
        if(productVo == null || productVo.getId() == null)
            return JSONResult.errorMsg("阴极板不存在!");

        if(StringUtils.isBlank(productVo.getProductCode()))
            return JSONResult.errorMsg("阴极板编码不能为空!");

        if(productVo.getProductValue() == null)
            return JSONResult.errorMsg("垂直度不能为空!");

        if(productVo.getProductState() == null)
            return JSONResult.errorMsg("阴极板状态不能为空!");

        Product product = new Product();
        product.setId(productVo.getId());
        product.setProductCode(productVo.getProductCode());
        product.setProductValue(productVo.getProductValue());
        if(productVo.getProductState().compareTo(MaintainType.Maintaining.getCode())==0){
            product.setMaintainType(productVo.getMaintainType());
            product.setUpdateMaintainDate(new Date());
        }else if(MaintainType.isLegal(productVo.getProductState())){
            return JSONResult.errorMsg("阴极板状态异常!");
        }
        product.setProductState(productVo.getProductState()); //阴极板状态更新
        product.setUserid(productVo.getUserid()); //阴极板状态更新人
        product.setUpdateStateDate(new Date()); //阴极板状态更新日期

        try {
            productService.updateProduct(product);
        } catch (Exception e) {
            return JSONResult.errorMsg(e.getMessage());
        }

        return JSONResult.ok();
    }

    @PostMapping("/addProduct")
    public JSONResult addProduct(@RequestBody Product product){
        if(product == null || StringUtils.isBlank(product.getProductCode()))
            return JSONResult.errorMsg("阴极板编码不能为空!");
        if(product.getProductValue() == null)
            return JSONResult.errorMsg("垂直度不能为空!");

        productService.addProduct(product);
        return JSONResult.ok();
    }

    @PostMapping("/deleteProduct")
    public JSONResult deleteProduct(@RequestBody Product product){
        if(product == null || product.getId() == null)
            return JSONResult.errorMsg("阴极板id不能为空!");

        productService.deleteProduct(product.getId());
        return JSONResult.ok();
    }

    @PostMapping("/checkProductCode")
    public JSONResult checkProductCode(@RequestBody ProductRequestParamVo productVo){
        if(productVo == null)
            return JSONResult.errorMsg("请求参数为空!");

        if(StringUtils.isBlank(productVo.getStartProductCode()))
            return JSONResult.errorMsg("阴极板起始编码不能为空!");

        if(StringUtils.isBlank(productVo.getEndProductCode()))
            return JSONResult.errorMsg("阴极板截止编码不能为空!");

        if(Long.valueOf(productVo.getStartProductCode()) > Long.valueOf(productVo.getEndProductCode()))
            return JSONResult.errorMsg("起始编码不能大于截止编码!");

        if(Long.valueOf(productVo.getEndProductCode()) - Long.valueOf(productVo.getStartProductCode()) >= 10000)
            return JSONResult.errorMsg("编码区间长度不能超过10000!");

        int count = productService.checkCount(productVo.getStartProductCode(),productVo.getEndProductCode());
        // if(count==0)
        //     return JSONResult.errorMsg("当前编码区间不存在阴极板!");

        int rcount = (int)(Long.valueOf(productVo.getEndProductCode())-Long.valueOf(productVo.getStartProductCode()))+1;
        if(rcount == count)
            return JSONResult.ok();

        List<Product> productList = productService.getAbsentList(productVo.getStartProductCode(),productVo.getEndProductCode());

        JSONResult jsonResult = new JSONResult();
        jsonResult.setStatus(504);
        jsonResult.setMsg("阴极板编码缺失!");
        jsonResult.setData(productList);
        return jsonResult;
    }

    /**
     * 将verticality_data表的数据导入到product表
     * 可能是废弃接口，未出现请求记录
     * @return
     */
    @GetMapping("/copyData")
    public JSONResult copyData(){

        List<VerticalityData> dataList = productService.getList();
        List<Product> productList = new ArrayList<>();
        for (VerticalityData verticalityData : dataList) {
            Product product = new Product();
            product.setProductCode(verticalityData.getVerticalityId());
            BigDecimal bigDecimal = new BigDecimal(String.valueOf(verticalityData.getVerticality()));
            product.setProductValue(bigDecimal.doubleValue());
            product.setProductState(MaintainType.Using.getCode());
            product.setCreatetime(verticalityData.getCreatetime());
            product.setUpdateStateDate(verticalityData.getCreatetime());
            productList.add(product);
        }
        productService.copyData(productList);

        return JSONResult.ok();
    }

    /**
     * 创建缺失的阴极板
     * @return
     */
    @PostMapping("/addProductList")
    public JSONResult addProductList(@RequestBody List<Product> productList){
        if(productList == null)
            return JSONResult.errorMsg("阴极板数据为空!");

        List<Product> addList = new ArrayList<>();
        for (Product product : productList) {
            if(product.getProductValue() == null || product.getProductValue() == 0)
                //product.setProductValue((double)0);
                continue;
            product.setProductState(MaintainType.Using.getCode());
            addList.add(product);
        }
        if(addList.size()>0)
            productService.addProductList(addList);

        return JSONResult.ok();
    }

    /**
     * 可能是废弃接口，未出现请求记录
     * @return
     */
    @GetMapping("/updateProductState")
    public JSONResult updateProductState(){
        Calendar calendar = new GregorianCalendar();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);

        List<ProjectSystem> projectSystemList = projectService.getProjects(hour);
        for (ProjectSystem projectSystem : projectSystemList) {
            String projectCode = projectSystem.getProjectCode();
            productService.updateProductState(projectCode);
        }

        return new JSONResult();
    }

    /**
     * 获取符合条件的阴极板数量
     * @param query
     * @param state
     * @param maintainType
     * @param factoryId
     * @param subFactoryId
     * @param userId
     * @return
     */
    @GetMapping("/getProductCount")
    public JSONResult getProductCount(String query,Integer state,Integer maintainType,String factoryId,String subFactoryId,String userId){
        if(StringUtils.isBlank(userId))
            return JSONResult.errorMsg("用户Id为空！");

        return JSONResult.ok(productService.getProductCount(query,state,maintainType,factoryId,subFactoryId,userId));

//        ProductVo queryVo = new ProductVo();
//        queryVo.setQuery(query);
//        queryVo.setProductState(state);
//        queryVo.setMaintainType(maintainType);
//        queryVo.setFactoryId(factoryId);
//        queryVo.setSubFactoryId(subFactoryId);
//        queryVo.setUserid(userId);
//
//        ProductVo productVo = productService.getProductCount(queryVo);
//        return JSONResult.ok(productVo);
    }

    @Deprecated
    @GetMapping("/getAllProductCounts")
    public JSONResult getAllProductCounts(String userId){
        if(StringUtils.isBlank(userId))
                return JSONResult.errorMsg("用户Id为空!");

        //List<ProductVo> productVoList = productService.getAllProductCounts(userId);
        List<ProductCountVo> countVos = productService.getProductCountByUserId(userId);

        ArrayList<JSONObject> jsonObjects = new ArrayList<>();

        for (ProductCountVo countVo : countVos) {
            JSONObject jsonObject = new JSONObject();
            //工厂名
            jsonObject.put("factoryName", countVo.getFactoryName());
            //总板数
            jsonObject.put("sum", (countVo.getOffline()+countVo.getMaintain()+countVo.getOnline()+countVo.getScrap()));
            //在线板数
            jsonObject.put("online", countVo.getOnline());
            //维修板数
            jsonObject.put("maintain", countVo.getMaintain());
            //备用板数
            jsonObject.put("offline", countVo.getOffline());
            //报废板数
            jsonObject.put("scrap", countVo.getScrap());
            //TODO 新增板数-今年对应的订单对应的product数量

            jsonObjects.add(jsonObject);
        }

        return JSONResult.ok(jsonObjects);
    }
    /**
     * 查询用户所属车间下所有状态的阴极板数量的统计
     */
    @GetMapping("/getClientProductCounts")
    public JSONResult getClientProductCounts(String userId){
        if(StringUtils.isBlank(userId))
            return JSONResult.errorMsg("用户Id为空!");

        //获取用户信息
        User user = userService.getUserById(userId);
        //查询用户所属车间下所有状态的阴极板数量的统计
        ProductCountVo count = productService.getProductCountBySubFactoryId(user.getSubFactoryId());

        //数据转换
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("subFactoryName", count.getFactoryName());//车间名
        jsonObject.put("sum", count.getSum());//总板数
        jsonObject.put("online", count.getOnline());//在线板数
        jsonObject.put("maintain", count.getMaintain());//维修板数
        jsonObject.put("offline", count.getOffline());//备用板数
        jsonObject.put("scrap", count.getScrap());//报废板数
        jsonObject.put("uncodeNum", count.getUncode());//无编码阴极板数量
        jsonObject.put("newAdd", count.getNewAdd());//新增阴极板数量
        jsonObject.put("cycle", factoryService.findById(user.getSubFactoryId()).getEquipCycle());//阴极周期

        return JSONResult.ok(jsonObject);
    }
//    /**
//     * 获取客户端阴极板管理相关数据
//     *
//     */
//    @Deprecated
//    @GetMapping("/getClientProductCounts")
//    public JSONResult getClientProductCounts(String userId){
//        if(StringUtils.isBlank(userId))
//            return JSONResult.errorMsg("用户Id为空!");
//
//        ProductVo productVo = productService.getClientProductCounts(userId);
//
//        return JSONResult.ok(productVo);
//    }
    /**
     * 查询用户拥有的某个订单下的阴极板简易信息
     */
    @GetMapping("/queryByProduct")
    public JSONResult queryByProduct(String projectId,Integer page,Integer pageSize) {

        if(page == null)
            page = 1;
        if(pageSize == null)
            pageSize = PAGE_SIZE;
        PageInfo<SimpleProductDTO> pageInfo = productService.queryByProjectId(projectId, page, pageSize);
        PagedResult pagedResult = new PagedResult();
        pagedResult.setPage(pageInfo.getPageNum());
        pagedResult.setTotal(pageInfo.getPages());
        pagedResult.setRecords(pageInfo.getTotal());
        //数据转换
        List<JSONObject> jsonObjects = new ArrayList<>();
        for(SimpleProductDTO info:pageInfo.getList()){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("productCode", info.getProduct_code()); //阴极板编码
            jsonObject.put("productValue", info.getProduct_value()); //垂直度
            jsonObject.put("createtime", info.getCreatetime()); //创建时间
            jsonObjects.add(jsonObject);
        }
        pagedResult.setRows(jsonObjects);
        return JSONResult.ok(pagedResult);
    }


    /**
     * 根据项目的项目编号去匹配相应的阴极板
     */
    @GetMapping("/getProductLikeCode")
    public JSONResult  getProductLikeCode(String projectCode,Integer page,Integer pageSize){
        if(page == null)
            page = 1;
        if(pageSize == null)
            pageSize = PAGE_SIZE;
        String productCode=projectCode;
        //阴极板编号前两位就是项目编号
        PageInfo<Product> pageInfo = productService.listProductByCode(productCode,page,pageSize);

        PagedResult pagedResult = new PagedResult();
        pagedResult.setPage(pageInfo.getPageNum());
        pagedResult.setTotal(pageInfo.getPages());
        pagedResult.setRecords(pageInfo.getTotal());
        //数据转换
        List<JSONObject> jsonObjects = new ArrayList<>();
        for(Product info:pageInfo.getList()){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("productCode", info.getProductCode()); //阴极板编码
            jsonObject.put("productValue", info.getProductValue()); //垂直度
            jsonObject.put("createtime", info.getCreatetime()); //创建时间
            jsonObjects.add(jsonObject);
        }
        pagedResult.setRows(jsonObjects);
        return JSONResult.ok(pagedResult);
    }
}
